<template>
  <a-card class="header-card h-full" :body-style="{ padding: '8px', height: '100%', display: 'flex', flexDirection: 'column' }">
    <div class="w-full flex justify-between">
      <!-- <SelectArea class="w-32" use-cache set-cache show-all @change="onChangeArea" /> -->
      <div class="w-1/4"></div>
      <a-radio-group v-model:value="patientStatus" button-style="solid" @change="onChangeTab">
        <a-radio-button value="4">待入院 ({{ patientStatusCount.dry || 0 }})</a-radio-button>
        <a-radio-button value="3">待入区 ({{ patientStatusCount.drq || 0 }})</a-radio-button>
        <a-radio-button value="0">在院 ({{ patientStatusCount.zy || 0 }})</a-radio-button>
        <a-radio-button value="2">待出院 ({{ patientStatusCount.dcy || 0 }})</a-radio-button>
        <a-radio-button value="31">退院 ({{ patientStatusCount.ty || 0 }})</a-radio-button>
        <a-radio-button value="1">已出院 ({{ patientStatusCount.ycy || 0 }})</a-radio-button>
      </a-radio-group>
      <div class="w-1/4">
        <div v-if="patientStatus == '0' || patientStatus == '2'" class="flex justify-end mr-2">
          <SelectArea
            v-if="patientStatus == '0'"
            v-model:value="areaValue"
            class="w-48 mr-2"
            use-cache
            set-cache
            post-url
            :post-params="{ wardTypeCodes: ['QYLB001', 'QYLB002'] }"
            @change="onChangeArea"
          />
          <a-radio-group v-model:value="isTableViewInRegistration" @change="listCardCheck">
            <a-tooltip title="列表模式" placement="bottom">
              <a-radio-button :value="true"><BarsOutlined /></a-radio-button>
            </a-tooltip>
            <a-tooltip title="卡片模式" placement="bottom">
              <a-radio-button :value="false"><AppstoreOutlined /></a-radio-button>
            </a-tooltip>
          </a-radio-group>
        </div>
      </div>
    </div>
    <div class="flex items-center my-2 justify-between">
      <!-- 左侧 -->
      <a-space v-if="patientStatus == '0'">
        <a-input-search v-model:value="value" class="w-80" placeholder="姓名/助记码/住院号/床位数" @search="queryList()" />
      </a-space>
      <a-space v-if="patientStatus == '1'" class="mt-4">
        <a-form-item label=" ">
          <a-input-search v-model:value="value" class="w-80" placeholder="姓名/助记码/住院号" @search="queryList()" />
        </a-form-item>
        <a-form-item label="出院日期">
          <a-range-picker v-model:value="searchDate" class="w-full" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="onQueryList()" />
        </a-form-item>
        <a-form-item name="" label="" class="ml-6">
          <a-radio-group v-model:value="chargeStatus" @change="queryList()">
            <a-radio value="">全部</a-radio>
            <a-radio value="1">已结账</a-radio>
            <a-radio value="3">已挂账</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-space>
      <a-space v-if="patientStatus == '2'">
        <a-input-search v-model:value="value" class="w-80" placeholder="姓名/助记码/住院号/床位数" @search="queryList()" />
      </a-space>
      <a-space v-if="patientStatus == '4'">
        <a-input-search v-model:value="value" class="w-80" placeholder="姓名/助记码/卡号/手机号/证件号码" @search="queryList()" />
      </a-space>
      <a-space v-if="patientStatus == '3'">
        <a-input-search v-model:value="value" class="w-80" placeholder="姓名/助记码/住院号" @search="queryList()" />
      </a-space>
      <!-- 右侧 -->
      <a-space v-if="patientStatus == '4'">
        <a-button type="primary" @click="queryList()">刷新</a-button>
        <a-button type="primary" @click="onShowEdit"> 入院登记 </a-button>
        <BaseExport type="住院" name="待入院" code="00001089" :search-params="exportParam">导出</BaseExport>
      </a-space>
      <a-space v-else-if="patientStatus == '0'">
        <div>隐藏空床</div>
        <a-switch v-model:checked="cardSwitch" class="ml-1 mr-3" @change="queryList()" />
        <a-button type="primary" @click="queryList()">刷新</a-button>
        <BaseExport type="住院" name="在院" code="00001090" :search-params="exportParam">导出</BaseExport>
      </a-space>
      <a-space v-else-if="patientStatus == '1'">
        <a-button type="primary" @click="queryList()">刷新</a-button>
        <BaseExport type="住院" name="已出院" code="00001091" :search-params="exportParam">导出</BaseExport>
      </a-space>
      <a-space v-else>
        <template v-if="patientStatus == '2'">
          <div>隐藏空床</div>
          <a-switch v-model:checked="cardSwitch" class="ml-1 mr-3" @change="queryList()" />
          <a-button type="primary" @click="queryList()">刷新</a-button>
          <BaseExport type="住院" name="待出院" code="000087" :search-params="exportParam">导出</BaseExport>
        </template>
        <template v-if="patientStatus == '3'">
          <a-button type="primary" @click="queryList()">刷新</a-button>
          <BaseExport type="住院" name="待入区" code="00001115" :search-params="exportParam">导出</BaseExport>
        </template>
      </a-space>
    </div>
    <!-- 表格 -->
    <!-- patientStatus为1，3,4固定位表格 patientStatus为0,2并且listOrCard为false时为卡片 -->
    <template v-if="patientStatus === '31'"> <CancelHospital /> </template>
    <BaseTable
      v-else-if="isTableViewInRegistration || patientStatus == '1' || patientStatus == '3' || patientStatus == '4'"
      :column-code="columnCode"
      :data-source="tableData"
      :loading="loading"
      fill
      bordered
      :scroll="{ x: formatTableWidth() }"
      :pagination="patientStatus == '1' ? { total: totalCount } : false"
      @change="({ current, pageSize }) => queryList(current, pageSize)"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'yyzt'">
          <a-tag v-if="record.yyzt == '0'" color="blue">有效</a-tag>
          <span v-if="record.yyzt == '1'" color="red">失效</span>
        </template>
        <template v-if="column.dataIndex === 'cyzt'">
          <span v-if="record.djzt == '0'">在院</span>
          <span v-if="record.djzt == '1'">已出院</span>
          <span v-if="record.djzt == '2'">待出院</span>
          <span v-if="record.djzt == '3'">待入区</span>
          <span v-if="record.djzt == '4'">待入院</span>
        </template>
        <template v-if="column.dataIndex === 'ryfs'">
          <span v-if="record.ryfs == '0'">门诊</span>
          <span v-if="record.ryfs == '1'">急诊</span>
          <span v-if="record.ryfs == '2'">其他医疗机构转入</span>
        </template>
        <template v-if="column.dataIndex === 'dischargeTime'">
          <span v-if="record.inpDischarge?.dischargeDate">{{ record.inpDischarge?.dischargeDate }}</span>
        </template>
        <template v-if="column.dataIndex === 'chargeStatusStr'">
          <a-tag v-if="record.chargeStatus == '0'" color="red">未结账</a-tag>
          <a-tag v-if="record.chargeStatus == '1'" color="blue">已结账</a-tag>
          <a-tag v-if="record.chargeStatus == '2'" color="red">退费中</a-tag>
          <a-tag v-if="record.chargeStatus == '3'" color="orange">已挂账</a-tag>
        </template>
        <template v-if="column.dataIndex === 'settlementAmount'">
          <span>{{ formatAmount(record.settlementAmount, 2) }}</span>
        </template>
        <template v-if="column.dataIndex === 'isNmiYbdj'">
          <span v-if="record.isNmiYbdj === 1">医保</span>
          <span v-if="record.isNmiYbdj === 0">自费</span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <!-- 待入院 -->
          <a-button v-if="patientStatus == '4'" size="small" type="link" @click="onRegister(record, true)"> 入院登记 </a-button>
          <a-divider v-if="patientStatus == '4'" type="vertical" />
          <BaseButton v-if="patientStatus == '4'" confirm-text="确定取消申请入院?" danger type="text" size="small" @click="onCancelInRegistration(record)">
            取消申请
          </BaseButton>
          <!-- 待入区 -->
          <a-button v-if="patientStatus == '3' && !isArmy" size="small" type="link" @click="openDepositModel(record, 1)"> 收取押金 </a-button>
          <template v-if="['0', '2', '3'].includes(patientStatus) && !isArmy">
            <a-button
              v-if="record.isNmiYbdj === 1"
              :disabled="getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '0'"
              size="small"
              type="link"
              danger
              @click="onClickMedical(record)"
            >
              撤销医保登记
            </a-button>
            <a-button
              v-if="record.isNmiYbdj === 0"
              :disabled="getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '0'"
              size="small"
              type="link"
              @click="onClickMedical(record)"
            >
              医保登记
            </a-button>
          </template>
          <a-button v-if="patientStatus == '3'" size="small" type="link" @click="onRegister(record, false)"> 修改登记 </a-button>
          <BaseButton v-if="patientStatus == '3'" confirm-text="确定取消入院?" danger type="text" size="small" @click="onCancelArea(record)">
            取消入院
          </BaseButton>
          <!-- <a-button v-if="patientStatus == '3'" @click="onCancelArea(record)">取消入院</a-button> -->
          <!-- 在院 -->
          <a-button v-if="patientStatus == '0' && !isArmy" type="link" size="small" @click="openDepositModel(record)"> 收取押金 </a-button>
          <!-- 待出院 -->
          <BaseButton v-if="patientStatus == '2'" type="link" size="small" :disabled="record.chargeStatus == 1" @click="onHospitalSettlement(record)">
            住院结算
          </BaseButton>
          <BaseButton v-if="patientStatus == '2'" type="link" size="small" @click="onPrintInventory(record)"> 住院清单 </BaseButton>
          <!-- 已出院 -->
          <div v-if="patientStatus == '1'">
            <a-button v-if="record.chargeStatus == '1' || record.chargeStatus == '2'" size="small" type="link" @click="onPrintBalance(record)">
              结算单据
            </a-button>
            <a-button v-if="record.chargeStatus == '1' || record.chargeStatus == '2'" size="small" type="link" @click="onPrintInventory(record)">
              住院清单
            </a-button>
            <a-button v-if="record.chargeStatus == '3'" size="small" type="link" @click="onOpenHospitalSettlement(record)"> 住院结算 </a-button>
            <TableMoreButton v-if="record.chargeStatus == '1' || record.chargeStatus == '2'">
              <a-button v-if="record.chargeStatus == '1' || record.chargeStatus == '2'" size="small" type="link" @click="onSupPrintMedical(record)">
                补打医保结算单
              </a-button>
            </TableMoreButton>
          </div>
        </template>
      </template>
    </BaseTable>

    <!-- 卡片 -->
    <div v-else-if="!isTableViewInRegistration" class="flex-1 overflow-y-auto">
      <div v-if="tableData">
        <div class="w-full flex flex-wrap content-start">
          <template v-for="(item, index) in tableData" :key="index">
            <a-dropdown v-if="item.brName" class="h-fit" trigger="contextmenu" :disabled="currentBed?.admissionCode !== item?.admissionCode">
              <PatientListCardCustom
                class="m-2"
                :data="item"
                :patient-status="patientStatus"
                show-footer
                :active="currentBed?.admissionCode === item?.admissionCode"
                @click="onRightClick(item)"
                @change-condition="onChangeCondition($event, item)"
              />
              <!-- 右键菜单 -->
              <template v-if="currentBed?.admissionCode === item?.admissionCode" #overlay>
                <a-menu>
                  <a-menu-item
                    v-for="menu in rightKeyMenus"
                    :key="menu.name"
                    :disabled="item.chargeStatus == 1 && menu.name == '住院结算'"
                    @click="menu.action(item)"
                    >{{ menu.name }}</a-menu-item
                  >
                </a-menu>
              </template>
            </a-dropdown>
            <a-dropdown v-else class="!h-auto" trigger="contextmenu">
              <BedCardEmpty class="m-2" :bed-code="item.bedCode" />
              <!-- 右键菜单 -->
            </a-dropdown>
          </template>
        </div>
      </div>
      <div v-else class="w-full h-full flex-center">
        <a-empty />
      </div>
      <a-spin v-if="loading" :spinning="true" class="w-full h-full flex-center absolute top-0 bg-white opacity-60" />
    </div>
    <Edit v-model:open="editOpen" :add-or-update="addOrUpdate" :row-data="rowData" @success="onEditSuccess" />
    <!-- 押金收费 -->
    <DepositModel
      v-model:open="depositModelOpen"
      :patient-info="{ ...patientInfo, settlementAmount: patientInfo.zyfy }"
      :charge-title="chargeTitle"
      :select-name-disabled="true"
      :deposit-type="0"
      @success="queryList()"
    />
    <!-- 退费弹窗 -->
    <ChargeModal
      v-model:open="returnChargeModel"
      :is-show-in-title="true"
      :charge-title="chargeTitle"
      :register-price="returnChargeInfo.returnJe"
      @success="onReturnSuccessPrice"
    />
    <!-- 医保登记 -->
    <MedicalRegistration
      v-model:open="medicalOpen"
      :patient-info="patientInfo"
      :charge-title="chargeTitle"
      :select-name-disabled="true"
      :deposit-type="0"
      @success="onEditSuccess"
    />
    <ChangeRegister v-model:open="changeOpen" :row-data="rowData" @success="onEditSuccess" />
  </a-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { formatAmount } from '@/utils/format'
import BaseButton from '@/components/BaseButton'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import ChargeModal from '@/components/ChargeModal/return'
import { getSystemConfig } from '@/utils/systemConfig'
import DepositModel from '@/views/in-registration/components/DepositModel.vue'
import MedicalRegistration from '../components/MedicalRegistration.vue'
import BedCardEmpty from './components/BedCardEmpty'
import ChangeRegister from './components/ChangeRegister'
import CancelHospital from './components/CancelHospital'
import Edit from './Edit'
import PatientListCardCustom from './components/PatientCard'

const router = useRouter()
const searchDate = ref([dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')])
const patientStatus = ref('4')
const rowData = ref(null)
const editOpen = ref(false)
const loading = ref(false)
const cardSwitch = ref(false)
const columnCode = ref('00001089')
const tableData = ref([])
const patientStatusCount = ref({})
const value = ref('')
const chargeStatus = ref('')
const changeOpen = ref(false)
const depositModelOpen = ref(false)
const medicalOpen = ref(false)
const patientInfo = ref({})
const areaValue = ref(undefined)
const chargeTitle = ref('')
const isTableViewInRegistration = ref(false) //true list  false card
const isArmy = ref(false) //是否jun用
const onShowEdit = () => {
  editOpen.value = true
  rowData.value = null
}
const currentBed = ref({})
const exportParam = ref({})
const returnChargeModel = ref(false)
const returnChargeInfo = ref({})
const rightKeyMenus = ref([])
const getTabList = async () => {
  const res = await post('inp/zydj/getPatientCountBylnpStatus', {
    bqbh: '',
    stdate: searchDate.value[0],
    eddate: searchDate.value[1]
  })
  patientStatusCount.value = res?.data || {}
}
const onEditSuccess = () => {
  changeOpen.value = false
  editOpen.value = false
  getTabList()
  queryList()
}

// 已出院选择时间
const onQueryList = () => {
  queryList()
}

const totalCount = ref(0)
const queryList = async (pageNum = 1, pageSize = getSystemConfig('DFFAULT_PAGE_SHOW_COUNT') || 10) => {
  tableData.value = []
  switch (patientStatus.value) {
    case '0': //在院
      columnCode.value = '00001090'
      break
    case '1': //已出院
      columnCode.value = '00001091'
      break
    case '2': //待出院
      columnCode.value = '000087'
      break
    case '3': //待入区
      columnCode.value = '00001115'
      break
    case '4': //待入院
      columnCode.value = '00001089'
      break
  }
  loading.value = true
  if (patientStatus.value === '4') {
    //待入院
    exportParam.value = {
      bqbh: areaValue.value,
      eddate: '',
      pyjm: value.value,
      stdate: '',
      yyzt: '0'
    }
    const res = await post('/inp/zydj/getInpAppointmentRecordList', exportParam.value)
    loading.value = false
    if (res.code !== 0) return message.error(res.msg)
    tableData.value = res.data
    totalCount.value = res.total
  } else {
    //卡片
    if (patientStatus.value === '0') {
      exportParam.value = {
        bqbh: areaValue.value,
        pyjm: value.value,
        hiddenEmptyBed: cardSwitch.value,
        statuss: [0, 2]
      }
      const res = await post('/inp/zyhs/getCwAndInpRecordList', exportParam.value)
      loading.value = false
      if (res.code !== 0) return message.error(res.msg)
      totalCount.value = res.total
      tableData.value = res.data
    } else {
      //非卡片
      exportParam.value = {
        bqbh: areaValue.value,
        pyjm: value.value,
        stdate: patientStatus.value === '1' ? searchDate.value[0] : undefined,
        eddate: patientStatus.value === '1' ? searchDate.value[1] : undefined,
        chargeStatus: patientStatus.value === '1' ? chargeStatus.value : undefined,
        status: patientStatus.value,
        hiddenEmptyBed: patientStatus.value === '2' ? cardSwitch.value : undefined
      }
      if (patientStatus.value === '1') {
        exportParam.value.pageNum = pageNum
        exportParam.value.pageSize = pageSize
      }
      const res = await post('/inp/zydj/getInpRecordList', exportParam.value)
      loading.value = false
      if (res.code !== 0) return message.error(res.msg)
      totalCount.value = res.total
      tableData.value = res.data
    }
  }
}

const onChangeTab = async (e) => {
  areaValue.value = undefined
  cardSwitch.value = false
  if (e.target.value !== '0') {
    queryList()
  }
  getTabList()
  patientStatus.value = e.target.value
  if (e.target.value === '0') {
    if (isArmy.value) {
      rightKeyMenus.value = []
    } else {
      rightKeyMenus.value = [
        { name: '医保登记', action: (item) => onClickMedical(item) },
        { name: '撤销医保登记', action: (item) => onClickMedical(item) },
        { name: '收取押金', action: (item) => openDepositModel(item) }
      ]
    }
  }
  if (e.target.value === '2') {
    rightKeyMenus.value = [
      { name: '住院结算', action: (item) => onHospitalSettlement(item) },
      { name: '住院清单', action: (item) => onPrintInventory(item) }
    ]
  }
}
const addOrUpdate = ref(true)
//入院登记
const onRegister = async (e, flag = true) => {
  editOpen.value = true
  addOrUpdate.value = flag
  if (flag) {
    rowData.value = e
  } else {
    rowData.value = {
      ...e,
      ...e.brxx,
      appDeptCode: e.lastDeptCode,
      wardId: e.lastWardId,
      bedCode: e.lastBedCode,
      dutyDoctorName: e.lastDutyDoctorName,
      dutyDoctor: e.lastDutyDoctor,
      inpDoctorName: e.lastInpDoctorName,
      inpDoctor: e.lastInpDoctor,
      attendingDoctorName: e.lastAttendingDoctorName,
      attendingDoctor: e.lastAttendingDoctor,
      directorDoctorName: e.lastDirectorDoctorName,
      directorDoctor: e.lastDirectorDoctor,
      memo: e.cmemo,
      zycs: e.inpFrequency,
      outpIco10codeName: e.ryzd,
      outpIco10code: e.icd10Code
    }
  }
}

// 取消入院-待入院
const onCancelInRegistration = async (row) => {
  const res = await post('/inp/zydj/doCancelInpAppointmentRecord?lsh=' + row.lsh)
  if (res.code !== 0) {
    message.error(res.msg || '操作失败')
  } else {
    message.success(res.msg)
    getTabList()
    queryList()
  }
}
//住院结算
const onHospitalSettlement = (e) => {
  router.push({
    path: '/in-registration/hospital-settlement',
    query: {
      lsh: e.inplsh
    }
  })
}
// 取消入院-待入区
const onCancelArea = async (row) => {
  returnChargeInfo.value = { ...row }
  returnChargeInfo.value.returnJe = row.dpJe
  const res = await post('/inp/inpComprehensive/getBillAmount', {
    inplsh: row.inplsh
  })
  if (res.code !== 0) {
    message.error(res.msg || '操作失败')
    return
  } else {
    chargeTitle.value = res.data.memo
    returnChargeModel.value = true
  }
}
//退费成功
const onReturnSuccessPrice = async (params) => {
  const res1 = await post('/inp/inpComprehensive/doReturnCharge', {
    typeOperation: '1',
    inplsh: returnChargeInfo.value.inplsh,
    ...params
  })
  if (res1.code !== 0) {
    message.error(res1.msg || '操作失败')
    return
  } else {
    const res = await post('/inp/zydj/doCancelInpStayZoneRecord', { inplsh: returnChargeInfo.value.inplsh }, { loading: true })
    if (res.code !== 0) {
      message.error(res.msg || '操作失败')
    } else {
      message.success(res.msg)
      returnChargeModel.value = false
      getTabList()
      queryList()
    }
  }
}

//病区选择事件
const onChangeArea = () => {
  queryList()
}
const onRightClick = (bed) => {
  currentBed.value = bed
}
const openDepositModel = async (row, type) => {
  depositModelOpen.value = true
  patientInfo.value = JSON.parse(JSON.stringify(row))
  // delete patientInfo.value.dpJe
  if (type === 1) {
    const res = await post('/inp/inpComprehensive/getBillAmount', {
      inplsh: row.inplsh
    })
    if (res.code !== 0) {
      message.error(res.msg || '操作失败')
      return
    } else {
      chargeTitle.value = res.data.memo
    }
  }
}

// 医保登记
const onClickMedical = (row) => {
  medicalOpen.value = true
  patientInfo.value = { ...row }
}

const onChangeCondition = (event, item) => {
  depositModelOpen.value = true
  patientInfo.value = item
}
const listCardCheck = (val) => {
  isTableViewInRegistration.value = val.target.value
  localStorage.setItem('isTableViewInRegistration', val.target.value)
  // cardSwitch.value = false
  queryList()
}
const onOpenHospitalSettlement = async () => {
  router.push({
    path: '/in-registration/hospital-settlement'
  })
}

const onPrintBalance = async (row) => {
  const { code, msg, data } = await post('/inp/Print/printSettlementDocumentsList', {
    inplsh: row?.inplsh
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 打印住院清单
const onPrintInventory = async (row) => {
  const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
    inplsh: row?.inplsh,
    jslb: 'SF'
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
//补打医保结算单
const onSupPrintMedical = async (row) => {
  const { code, msg, data } = await post('/inp/Print/printFeeStatements', { inplsh: row?.inplsh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
const formatTableWidth = () => {
  if (patientStatus.value === '1') {
    return 4300
  } else {
    2300
  }
}

// 打印结算单据
// const onPrintBalance = () => {
//   const { code, msg, data } = await post('/inp/Print/printAdmissionList', {
//     inplsh: row?.inplsh,
//     jslb: 'SF'
//   })
//   if (code !== 0) return message.error(msg)
//   window.openExe?.rpt(data) //调用winform打印
// }

onMounted(() => {
  isTableViewInRegistration.value = localStorage.getItem('isTableViewInRegistration') === 'true'
  getTabList()
  queryList()
  isArmy.value = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
})
</script>
